package cc.ufinity.networkdiagnose.widget;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import cc.ufinity.networkdiagnose.view.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class TaskWidget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
	
	private Activity ctx;
	private TaskParser taskParser;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;

	public TaskWidget(Activity context) {
		super(context);
		this.ctx = context;
		inflate(context, R.layout.task_widget, this);
		taskListView = (ListView) this.findViewById(R.id.taskListView);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				Task task = (Task) r.get("task");
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
				SelectNetType st = new SelectNetType(ctx);
				ctx.setContentView(st);
				//TaskDetailWidget tdw = new TaskDetailWidget(ctx);
				//ctx.setContentView(tdw);
			}

		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				}
			}
		};

		tm = new TelManager(ctx);
		tm.setHandler(handler);
	}

	public void start() {
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		 myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
		inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");

						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() {

		SimpleAdapter adapter = new SimpleAdapter(ctx, datas, R.layout.task_list_widget, 
				new String[] { "taskName", "apName", "taskType", "taskDesc" ,"taskApnum"}, //名称、热点、类型、描述
				new int[] { R.id.task_name, R.id.ap_name, R.id.task_type , R.id.task_desc,R.id.task_apnum }); 
		taskListView.setAdapter(adapter);
	}
	
	/*private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		taskParser = new PullTaskParser();
		String labelTaskName = this.getResources().getString(
				R.string.label_task_name);
		String labelTaskType = this.getResources().getString(
				R.string.label_task_type);
		String labelTaskDesc = this.getResources().getString(
				R.string.label_task_desc);
		String labelApName = this.getResources().getString(
				R.string.label_apname);

		try {
			tasks = new ArrayList<Task>();
			for(int i=0; i<5; i++) {
				Task tk = new Task();
				tk.id = i;
				tk.taskName = i + "";
				tk.apName = i + "";
				tk.taskType = "巡检测试";
				tk.taskDes = "智畅信息";
				tk.taskMan = "测试员";
				tk.remark = "室内";
				tasks.add(tk);
			}
			
			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", labelTaskName + task.taskName);
				t.put("apName", labelApName + task.apName);
				t.put("taskType", labelTaskType + task.taskType);
				t.put("taskDesc", labelTaskDesc + task.taskDes);
				t.put("task", task);
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}
*/
	 private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		taskParser = new PullTaskParser();
		String labelTaskName = this.getResources().getString(
				R.string.label_task_name);
		String labelTaskType = this.getResources().getString(
				R.string.label_task_type);
		String labelTaskDesc = this.getResources().getString(
				R.string.label_task_desc);
		String labelApName = this.getResources().getString(
				R.string.label_apname);
		String labelApNum = this.getResources().getString(
				R.string.label_task_apnum);
		// String path = "cc/ufinity/networkdiagnose/widget/tasks.xml";
		String url = "http://221.130.165.252/Task/ReturnXML.aspx";
		Log.d("Task", "my phone number is:" + myPhoneNumber);
		String requrl = url + "?TaskPhone=" + "13637050391";
		try {
			InputStream is = HttpUtils.getInputStream(requrl);
			tasks = taskParser.parse(is);
			Map<String, Object> t = null;
			for (Task task : tasks) {
				List<Map<String, String>> apList = task.apList;
				int apNum = apList!=null?apList.size():0;
				String tempString ="已完成测试AP/待测试AP(单位：个)：0/"+apNum;
				t = new HashMap<String, Object>();
				t.put("taskName", labelTaskName + task.taskName);
				t.put("apName", labelApName + task.apName);
				t.put("taskType", labelTaskType + task.taskType);
				t.put("taskDesc", labelTaskDesc + task.taskDes);
				t.put("taskApnum", labelApNum +tempString);
				t.put("task", task);
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}

}
